package com.yinhe.music.yhmusic.main.my;

import android.util.Log;

import com.chad.library.adapter.base.entity.MultiItemEntity;
import com.yinhe.music.common.utils.JsonUtil;
import com.yinhe.music.yhmusic.base.BaseModel;
import com.yinhe.music.yhmusic.constants.IConstants;
import com.yinhe.music.yhmusic.db.DataBaseAccessor;
import com.yinhe.music.yhmusic.db.bean.MenuDBEntity;
import com.yinhe.music.yhmusic.log.BlankUtil;
import com.yinhe.music.yhmusic.model.MyTitleItem;
import com.yinhe.music.yhmusic.model.SongMenuList;

import java.util.ArrayList;
import java.util.List;

/**
 * 我的界面M层
 *
 * @author 何晓华
 */
public class MyModel extends BaseModel implements MyContract.IMyModel {

    @Override
    public List<MultiItemEntity> getLocalMenuData() {
        List<MenuDBEntity> menuDBEntityList = DataBaseAccessor.getInstance().getAllMenuSyn();

        ArrayList<MultiItemEntity> res = new ArrayList<>();
        MyTitleItem item1 = new MyTitleItem("我创建的歌单", "0");
        MyTitleItem item2 = new MyTitleItem("我收藏的歌单", "0");

        if (menuDBEntityList != null) {
            for (MenuDBEntity menuDBEntity : menuDBEntityList) {
                if (menuDBEntity.getType() == IConstants.CREATE_MENU) {
                    item1.addSubItem(new SongMenuList(menuDBEntity));
                } else {
                    item2.addSubItem(new SongMenuList(menuDBEntity));
                }
            }

            if (!BlankUtil.isBlank(item1.getSubItems())) {
                item1.setCount(String.valueOf(item1.getSubItems().size()));
            }

            if (!BlankUtil.isBlank(item2.getSubItems())) {
                item2.setCount(String.valueOf(item2.getSubItems().size()));
            }
        }

        res.add(item1);
        res.add(item2);

        return res;
    }

    @Override
    public List<MultiItemEntity> getLocalVisitorData() {

        MenuDBEntity menuDBEntity = new MenuDBEntity(0, "我喜欢的", "", 0);
        ArrayList<MultiItemEntity> res = new ArrayList<>();
        MyTitleItem item1 = new MyTitleItem("我创建的歌单", "0");
        item1.addSubItem(new SongMenuList(menuDBEntity));

        res.add(item1);
        return res;
    }

    @Override
    public void doSyn(List<SongMenuList> list, int type) {
        List<MenuDBEntity> addList = new ArrayList<>();

        for (int i = 0; i < list.size(); i++) {
            SongMenuList info = list.get(i);
            MenuDBEntity menuDBEntity = new MenuDBEntity(info, type);
            if (DataBaseAccessor.getInstance().isExistIdSyn(info.getSongMenuId())) {
                MenuDBEntity loaclMenuDBEntity = DataBaseAccessor.getInstance().getMenuByIdSyn(info.getSongMenuId());
                menuDBEntity.setSongIds(loaclMenuDBEntity.getSongIds());
                menuDBEntity.setSongnum(loaclMenuDBEntity.getSongnum());
            }
            addList.add(menuDBEntity);
        }

        if (!addList.isEmpty()) {
            DataBaseAccessor.getInstance().insertMenuList(addList);
        }
    }
}
